package _2_leetcode_21_40._38外观数列;

/**
 * User: Mazexal
 * Date: 2021/1/24
 */
public class Solution {

    public String countAndSay(int n) {

        StringBuffer readVal = new StringBuffer().append("1");
        if (n == 1) {
            return readVal.toString();
        }

        for (int i = 1; i < n; i++) {
            StringBuffer sb = new StringBuffer();
            // 前次值
            char preReadVal = readVal.charAt(0);
            // 重复次数
            int count = 1;
            for (int j = 1; j < readVal.length(); j++) {
                // 当前值
                char currentReadVal = readVal.charAt(j);
                if (preReadVal == currentReadVal) {
                    // 前后值相等，计数加一
                    count++;
                } else {
                    // count个preInt。例：111读作31表示3个1
                    sb.append(count).append(preReadVal);
                    // 重置
                    preReadVal = currentReadVal;
                    count = 1;
                }
            }
            // 最后一次计数处理
            sb.append(count).append(preReadVal);
            readVal = sb;
            sb = null;
        }

        return readVal.toString();
    }
}
